<?php

use Illuminate\Database\Capsule\Manager as DB;

abstract class CoreController extends Yaf_Controller_Abstract
{
    protected $module;
    protected $controller;
    protected $action;
    protected $method;
    protected $files;
    protected $curr_url;
    protected $config;
    protected $session;
    protected $auth;
    protected $pageParam;
    protected $postData;

    /**
     * 初始化
     *
     */
    public function init()
    {
        Yaf_Dispatcher::getInstance()->disableView();
        $Request          = Yaf_Dispatcher::getInstance()->getRequest();
        $this->module     = $Request->getModuleName();
        $this->controller = $Request->getControllerName();
        $this->action     = $Request->getActionName();
        $this->method     = $Request->getMethod();
        $this->curr_url   = $Request->getRequestUri();
        $this->config     = Yaf_Application::app()->getConfig();
        $this->session    = Yaf_Session::getInstance();
        $this->postData   = $this->getPost();
        $this->pageParam  = array_merge($this->getQuery(), $this->getParam(), $this->getPost());
    }

    /**
     * get one parameter
     * @param string $name
     * @param string $default
     * @return array|string|unknown_type
     * ex: $this->get('imgs/a');    //array
     * ex: $this->get('age/d');     //integer
     * ex: $this->get('height/f');  //float
     * ex: $this->get('gender/b');  //bool
     * ex: $this->get('name/s');    //sting
     */
    protected function get($name = '', $default = '')
    {
        if (empty($name)) {
            return $this->pageParam;
        } else {
            if (strpos($name, '?') === false) {
                if (strpos($name, '/')) {
                    [$name, $type] = explode('/', $name);
                }
                $value = $this->pageParam[$name] ?? $default;
                $value = Tools::filter($value);
                if (is_null($value)) {
                    return $default;
                }
                if (is_object($value)) {
                    return $value;
                }
                if (isset($type) && $value !== $default) {
                    // 强制类型转换
                    $this->typeCast($value, $type);
                }
                return $value;
            } else {
                return isset($this->pageParam[str_replace('?', '', $name)]);
            }
        }
    }

    /**
     * 强制类型转换
     * @access public
     * @param string $data
     * @param string $type
     * @return mixed
     */
    private function typeCast(&$data, $type)
    {
        switch (strtolower($type)) {
            // 数组
            case 'a':
                $data = (array)$data;
                break;
            // 数字
            case 'd':
                $data = (int)$data;
                break;
            // 浮点
            case 'f':
                $data = (float)$data;
                break;
            // 布尔
            case 'b':
                $data = (boolean)$data;
                break;
            // 字符串
            case 's':
                if (is_scalar($data)) {
                    $data = (string)$data;
                } else {
                    throw new \InvalidArgumentException('variable type error：' . gettype($data));
                }
                break;
        }
    }

    /**
     * @param string $name
     * @param string $default
     * @return array|string|unknown_type
     */
    protected function input($name = '', $default = '')
    {
        return $this->get($name, $default);
    }

    /**
     * Get
     * @param string $name
     * @param string $default
     * @return array|unknown_type
     */
    protected function getQuery($name = '', $default = '')
    {
        if (empty($name)) {
            return $this->getRequest()->getQuery();
        } else {
            $value = $this->getRequest()->getQuery($name, $default);
            $value = Tools::filter($value);
            return $value;
        }
    }

    /**
     * GetParams
     * @param string $name
     * @param string $default
     * @return array|mixed|unknown_type
     */
    protected function getParam($name = '', $default = '')
    {
        if (empty($name)) {
            return $this->getRequest()->getParams();
        } else {
            $value = $this->getRequest()->getParam($name, $default);
            $value = Tools::filter($value);
            return $value;
        }
    }

    /**
     * Post
     * @param string $name
     * @param string $default
     * @return array|mixed|unknown_type
     */
    protected function getPost($name = '', $default = '')
    {
        $json = $this->parse_json(file_get_contents("php://input"));
        if (empty($json)) {
            if (empty($name)) {
                return $this->getRequest()->getPost();
            } else {
                $value = $this->getRequest()->getPost($name, $default);
                $value = Tools::filter($value);
                return $value;
            }
        } else {
            if (empty($name)) {
                return $json;
            } else {
                $value = $json[$name];
                $value = Tools::filter($value);
                return $value;
            }
        }
    }

    protected function parse_json($string)
    {
        $json = json_decode($string, TRUE);
        if (json_last_error() == JSON_ERROR_NONE) {
            return $json;
        } else {
            return [];
        }
    }

    /**
     * request
     * @param string $name
     * @param string $default
     * @return array|unknown_type
     */
    protected function getCookie($name = '', $default = '')
    {
        $value = $this->getRequest()->getCookie($name, $default);
        $value = Tools::filter($value);
        return $value;
    }

    /**
     * files
     * @param $name
     * @return
     */
    protected function getFiles($name)
    {
        if (empty($name)) {
            return $this->getRequest()->getFiles();
        } else {
            return $this->getRequest()->getFiles($name);
        }
    }

    protected function isXml()
    {
        return $this->getRequest()->isXmlHttpRequest();
    }

    protected function isPost()
    {
        return $this->getRequest()->isPost();
    }

    protected function isPut()
    {
        return $this->getRequest()->isPut();
    }

    protected function isGet()
    {
        return $this->getRequest()->isGet();
    }

    /**
     *记录SQL日志
     *前置 DB::enableQueryLog();
     */
    protected function sqlLog()
    {
        $sqllogs = DB::getQueryLog();
        foreach ($sqllogs as $onesql) {
            $query    = str_replace('?', '%s', $onesql['query']);
            $bindings = $onesql['bindings'];
            array_walk($bindings, function (&$v) {
                $v = "'$v'";
            });

            array_unshift($bindings, $query);
            $sql = call_user_func_array('sprintf', $bindings);
            \Log::out('sql', 'I', call_user_func_array('sprintf', $bindings));
        }
    }

    #上传base64图片字符串
    protected function uploadImgByBase64(string $base64str)
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64str, $base64result)) {
            $ext      = $base64result[2];
            $ext      = stristr($ext, 'jpeg') ? 'jpg' : $ext;
            $config   = Yaf_Registry::get('config');
            $fileName = 'img-t' . time() . rand(10000, 99999) . '.' . $ext;
            $path     = '/logo/' . date('Ym') . '/';
            $desdir   = $config['application']['uploadpath'] . $path;
            if (!is_dir($desdir)) {
                mkdir($desdir, 0777, TRUE);
            }
            $realpath = $desdir . $fileName;

            if (file_put_contents($realpath, base64_decode(str_replace(' ', '+', str_replace($base64result[1], '', $base64str))))) {
                if ($image = $this->putToCDN($desdir . $fileName, $fileName)) {
                    return $image;
                }
            }
        }
        return FALSE;
    }

    /***上传图片文件**
     * @param $upfile
     * @return array|bool
     * @throws Exception
     */
    protected function uploadImgByFile(string $upfile)
    {
        $files = $this->getFiles($upfile);
        if ($files != NULL && $files['size'] > 0) {
            $uploader = new FileUploader();
            $files    = $uploader->getFile($upfile);
            if (!$files) {
                return FALSE;
            }
            if ($files->getSize() == 0) {
                return FALSE;
            }
            $config = Yaf_Registry::get('config');
            if (!$files->checkExts($config['application']['upfileExts'])) {
                return FALSE;
            }
            if (!$files->checkSize($config['application']['upfileSize'])) {
                return FALSE;
            }
            $cdnfilename = 'Images-t' . time() . rand(100, 999) . '.' . $files->getExt();
            if ($image = $this->putToCDN($files->getTmpName(), $cdnfilename)) {
                $rows = [
                    "originalName" => $files->getFilename(),
                    "name"         => $cdnfilename,
                    "url"          => $image,
                    "size"         => $files->getSize(),
                    "type"         => $files->getMimeType(),
                    "state"        => 'SUCCESS'
                ];
                return $rows;
            }
        }
        return FALSE;
    }

    /***PHP上传文件到七牛cdn**
     * @param $filePath
     * @param $cdnfileName
     * @return bool|string
     * @throws Exception
     */
    protected function putToCDN($filePath, $cdnfileName)
    {
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = $this->config['application']['cdn']['accessKey'];
        $secretKey = $this->config['application']['cdn']['secretKey'];

        // 构建鉴权对象
        $auth = new \Qiniu\Auth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = $this->config['application']['cdn']['bucket'];

        // 生成上传 Token
        $token = $auth->uploadToken($bucket);

        // 上传到七牛后保存的文件名
        $key = $cdnfileName;

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new \Qiniu\Storage\UploadManager;

        // 调用 UploadManager 的 putFile 方法进行文件的上传
        [$ret, $err] = $uploadMgr->putFile($token, $key, $filePath);

        if ($err !== null) {
            return false;
        } else {
            return $this->config['application']['cdn']['url'] . $ret['key'];
        }
    }

}
